package com.qd.panda.service.card;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.cdqidi.constant.ConstantDto;
import com.cdqidi.db.BaseService;
import com.cdqidi.dto.CacheKey;
import com.cdqidi.exception.ApiException;
import com.cdqidi.util.RedisTemplateUtil;
import com.qd.common.panda.config.PandaParkConfigDTO;
import com.qd.common.panda.constant.PandaConstant;
import com.qd.common.panda.domain.entity.card.UserCardDTO;
import com.qd.common.panda.domain.entity.card.UserCardQueryDTO;
import com.qd.common.panda.domain.entity.card.UserCardReminderDTO;
import com.qd.common.sys.domain.sendmsg.FusionMsg;
import com.qd.common.sys.domain.sendmsg.MsgReceiver;
import com.qd.panda.mapper.card.UserCardMapper;
import com.qd.panda.model.UserCard;
import com.qd.system.service.msg.client.FusionMsgClientService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

/**
 * 我的卡卷
 *
 * @author sjk
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class UserCardService extends BaseService<UserCardMapper, UserCard> {

    private static final String PREFIX_ID = "panda_user_card_cardId_{0}";

    private final RedisTemplateUtil<UserCard> redisTemplateUtil;
    private final CardInfoService cardInfoService;
    @Resource
    private FusionMsgClientService fusionMsgClientService;
    @Resource
    private PandaParkConfigDTO parkConfigDTO;

    /**
     * 保存
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public UserCardDTO save(UserCardDTO dto) {
        final UserCard model = dtoToModel(dto);
        try {
            if (super.save(model)) {
                return modelToDto(model);
            }
            throw new ApiException("添加失败");
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 修改
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public UserCardDTO update(UserCardDTO dto) {
        final UserCard historyModel = Optional.ofNullable(getById(dto.getCardId())).orElseThrow(() -> new ApiException("ID不存在,不能更新"));
        final UserCard model = dtoToModel(dto);
        try {
            if (super.updateById(model)) {
                return modelToDto(model);
            }
            throw new ApiException("更新失败");
        } finally {
            clearCache(historyModel);
            historyModel.freeData();
            model.freeData();
        }
    }

    /**
     * 批量添加
     *
     * @param mList 数据库对象
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveBatch(List<UserCard> mList) {
        try {
            if (!super.saveBatch(mList)) {
                throw new ApiException("批量添加失败");
            }
        } finally {
            clearCaches(mList);
        }
    }

    /**
     * 批量更新
     *
     * @param mList 数据库对象
     */
    public void updateBatchIds(List<UserCard> mList) {
        final List<String> ids = mList.stream().map(UserCard::getCardId).collect(toList());
        final List<UserCard> historyModelList = checkIds(ids);
        try {
            if (!super.updateBatchById(mList)) {
                throw new ApiException("批量更新失败");
            }
        } finally {
            clearCaches(historyModelList);
            historyModelList.clear();
            ids.clear();
        }
    }

    /**
     * 删除，单个
     *
     * @param cardId 主键
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeById(String cardId) {
        final UserCard historyModel = Optional.ofNullable(getById(cardId)).orElseThrow(() -> new ApiException("数据不存在,不能删除"));
        try {
            if (!super.removeById(cardId)) {
                throw new ApiException("删除失败");
            }
        } finally {
            clearCache(historyModel);
            historyModel.freeData();
        }
    }

    /**
     * 批量删除
     *
     * @param ids 主键集合
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeBatchIds(List<String> ids) {
        final List<UserCard> historyModelList = checkIds(ids);
        try {
            if (!super.removeByIds(ids)) {
                throw new ApiException("批量删除失败");
            }
        } finally {
            clearCaches(historyModelList);
            historyModelList.clear();
        }
    }

    /**
     * 根据传入对象构建查询参数，判断是否存在
     *
     * @param dto 参数
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExists(UserCardDTO dto) {
        final QueryWrapper<UserCard> queryWrapper = createQueryWrapper(dto);
        final boolean exists = super.count(queryWrapper) > 0;
        queryWrapper.clear();
        return exists;
    }

    /**
     * 根据主键判断数据是否存在
     *
     * @param cardId 主键
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExistsById(String cardId) {
        boolean exists = false;
        if (StringUtils.hasLength(cardId)) {
            final UserCard model = getById(cardId);
            exists = (null != model);
            if (exists) {
                model.freeData();
            }
        }
        return exists;
    }

    /**
     * 根据主键获取数据
     *
     * @param cardId 主键
     * @return 单条记录
     */
    public UserCard getById(String cardId) {
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, cardId);
        return redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> super.getById(cardId), UserCard.class);
    }

    /**
     * 根据主键获取数据
     *
     * @param cardId 主键
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public UserCardDTO getByIdDto(String cardId) {
        return Optional.ofNullable(getById(cardId)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录
     */
    public UserCard getOne(UserCardDTO dto) {
        final QueryWrapper<UserCard> queryWrapper = createQueryWrapper(dto);
        UserCard model = super.getOne(queryWrapper);
        queryWrapper.clear();
        return model;
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public UserCardDTO getOneDto(UserCardDTO dto) {
        return Optional.ofNullable(getOne(dto)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据
     */
    public List<UserCard> getList(UserCardDTO dto) {
        final QueryWrapper<UserCard> queryWrapper = createQueryWrapper(dto);
        final List<UserCard> list = super.list(queryWrapper);
        queryWrapper.clear();
        return list;
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据，转换成页面对象
     */
    @Transactional(readOnly = true)
    public List<UserCardDTO> getListDto(UserCardDTO dto) {
        return modelToDtoList(getList(dto));
    }

    /**
     * 分页数据
     *
     * @param page 分页对象
     * @param dto  查询参数
     * @return 分页信息
     */
    @Transactional(readOnly = true)
    public IPage<UserCardDTO> page(Page<UserCard> page, UserCardQueryDTO dto) {
        final QueryWrapper<UserCard> queryWrapper = buildQuery(dto);
        final IPage<UserCardDTO> iPage = baseMapper.page(page, queryWrapper, dto.getState());
        Optional.ofNullable(iPage.getRecords()).ifPresent(r->r.forEach(this::buildDisplay));
        queryWrapper.clear();
        return iPage;
    }

    /**
     * 列表
     *
     * @param dto  查询参数
     * @return 分页信息
     */
    @Transactional(readOnly = true)
    public List<UserCardDTO> list(UserCardQueryDTO dto) {
        final QueryWrapper<UserCard> queryWrapper = buildQuery(dto);
        queryWrapper.isNull("t6.third_party");
        final List<UserCardDTO> list = baseMapper.list(queryWrapper);
        queryWrapper.clear();
        return list;
    }

    /**
     * 可用优惠卷数量
     *
     * @param dto 查询参数
     * @return 数量
     */
    @Transactional(readOnly = true)
    public Long availableSize(UserCardQueryDTO dto) {
        final QueryWrapper<UserCard> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", dto.getUserId());
        queryWrapper.eq("state", PandaConstant.USE_STATE_1);
        queryWrapper.ge("validity_end_time", LocalDate.now());
        Long count = getBaseMapper().selectCount(queryWrapper);
        queryWrapper.clear();
        return SqlHelper.retCount(count);
    }

    private QueryWrapper<UserCard> buildQuery(UserCardQueryDTO dto) {
        final QueryWrapper<UserCard> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("t1.user_id", dto.getUserId());
        if (null != dto.getState() && dto.getState() > 0) {
            if(dto.getState() == 3){
                //已过期，查询条件需要加上近一个月
                queryWrapper.gt("validity_end_time",LocalDate.now().plusDays(-31));
            }
            if(dto.getState()==1){
                queryWrapper.groupBy("t1.card_id");
            }
            queryWrapper.eq("t1.state", dto.getState());
        }
        if (StringUtils.hasLength(dto.getCardType())) {
            queryWrapper.in("t2.card_type", dto.getCardType(), PandaConstant.CARD_TYPE_ALL);
        }
        if (StringUtils.hasLength(dto.getUseBrand())) {
            queryWrapper.in("t2.use_brand", dto.getUseBrand(), PandaConstant.ALL);
        }
        queryWrapper.orderByAsc("t1.validity_end_time");
        queryWrapper.orderByAsc("t2.card_type");
        queryWrapper.orderByDesc("t2.discount_amount");
        return queryWrapper;
    }

    /**
     * 清空缓存
     *
     * @param model 数据库对象
     */
    public void clearCache(UserCard model) {
        if (null == model) {
            return;
        }
        redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getCardId()));
    }

    /**
     * 批量清空缓存
     *
     * @param list 数据库对象
     */
    public void clearCaches(List<UserCard> list) {
        if (null == list || list.isEmpty()) {
            return;
        }
        List<String> ids = list.stream().map(model -> RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getCardId())).collect(toList());
        if (!ids.isEmpty()) {
            redisTemplateUtil.deleteByKey(ids);
            ids.clear();
        }
    }

    /**
     * 数据库对象转页面对象
     *
     * @param model 数据库对象
     * @return 页面对象
     */
    public UserCardDTO modelToDto(UserCard model) {
        if (null == model) {
            return null;
        }
        final UserCardDTO dto = new UserCardDTO();
        dto.setCardId(model.getCardId());
        dto.setRedemptionTime(model.getRedemptionTime());
        dto.setUseTime(model.getUseTime());
        dto.setState(model.getState());
        dto.setCardMsgId(model.getCardMsgId());
        dto.setUserId(model.getUserId());
        dto.setOrderId(model.getOrderId());
        dto.setValidityEndTime(model.getValidityEndTime());
        dto.setSystemDistribution(model.getSystemDistribution());
        buildDisplay(dto);
        return dto;
    }

    /**
     * 页面对象转数据库对象
     *
     * @param dto 页面对象
     * @return 数据库对象
     */
    public UserCard dtoToModel(UserCardDTO dto) {
        if (null == dto) {
            return null;
        }
        final UserCard model = new UserCard();
        model.setCardId(dto.getCardId());
        model.setRedemptionTime(dto.getRedemptionTime());
        model.setUseTime(dto.getUseTime());
        model.setState(dto.getState());
        model.setCardMsgId(dto.getCardMsgId());
        model.setUserId(dto.getUserId());
        model.setOrderId(dto.getOrderId());
        model.setValidityEndTime(dto.getValidityEndTime());
        model.setSystemDistribution(dto.getSystemDistribution());
        return model;
    }

    /**
     * 码表转换
     *
     * @param dto 页面对象
     */
    public void buildDisplay(UserCardDTO dto) {
        Optional.ofNullable(cardInfoService.getByIdDto(dto.getCardMsgId())).ifPresent(dto::setCardInfoDTO);
    }

    /**
     * 数据库对象转页面对象
     *
     * @param list 数据库对象
     * @return 页面对象
     */
    public List<UserCardDTO> modelToDtoList(List<UserCard> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::modelToDto).collect(toList());
    }

    /**
     * 页面对象转数据库对象
     *
     * @param list 页面对象
     * @return 数据库对象
     */
    public List<UserCard> dtoToModelList(List<UserCardDTO> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::dtoToModel).collect(toList());
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto 查询参数，不为空的属性会被自动加入
     */
    public QueryWrapper<UserCard> createQueryWrapper(UserCardDTO dto) {
        return createQueryWrapper(dto, "");
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto        查询参数，不为空的属性会被自动加入
     * @param tableAlias 表别名
     */
    public QueryWrapper<UserCard> createQueryWrapper(UserCardDTO dto, String tableAlias) {
        final QueryWrapper<UserCard> queryWrapper = new QueryWrapper<>();
        if (null != dto) {
            if (StringUtils.hasLength(tableAlias) && tableAlias.charAt(tableAlias.length() - 1) != '.') {
                tableAlias += ".";
            }
            if (StringUtils.hasLength(dto.getCardMsgId())) {
                queryWrapper.eq(tableAlias + "card_msg_id", dto.getCardMsgId());
            }
            if (StringUtils.hasLength(dto.getUserId())) {
                queryWrapper.eq(tableAlias + "user_id", dto.getUserId());
            }
        }
        return queryWrapper;
    }

    /**
     * 批量检查主键在数据库中是否存在
     *
     * @param ids 主键集合
     * @return 主键查询出来的集合
     */
    public List<UserCard> checkIds(List<String> ids) {
        if (null == ids || ids.isEmpty()) {
            throw new ApiException("ids不能为空");
        }
        final List<UserCard> list = super.listByIds(ids);
        if (list.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(ids.toArray()));
        }
        if (ids.size() == list.size()) {
            return list;
        }
        List<String> dbIds = list.stream().map(UserCard::getCardId).collect(toList());
        final List<String> notExistsList = ids.stream().filter(id -> !dbIds.contains(id)).collect(toList());
        dbIds.clear();
        if (!notExistsList.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(notExistsList.toArray()));
        }
        return list;
    }

    /**
     * 清理过期的卷数据
     *
     * @param localDate 时间
     */
    @Transactional(rollbackFor = Exception.class)
    public void clearUpCard(LocalDate localDate) {
        List<UserCardDTO> userCardList = getBaseMapper().overdueList(localDate, PandaConstant.USE_STATE_1);
        if (!userCardList.isEmpty()) {
            List<UserCard> modelList = userCardList.stream().map(userCardDTO -> {
                UserCard userCard = dtoToModel(userCardDTO);
                return userCard.setState(PandaConstant.USE_STATE_3);
            }).collect(Collectors.toList());
            updateBatchIds(modelList);
            modelList.clear();
            userCardList.clear();
        }
    }

    @Transactional(readOnly = true)
    public boolean isExistsCardMsgId(String cardMsgId,String userId) {
        QueryWrapper<UserCard> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("card_msg_id",cardMsgId);
        queryWrapper.eq("user_id",userId);
        boolean exists = getBaseMapper().exists(queryWrapper);
        queryWrapper.clear();
        return exists;
    }

    @Transactional(readOnly = true)
    public void reminder(LocalDate now) {
        LocalDate localDate = now.plusDays(2);
        List<UserCardReminderDTO> list = getBaseMapper().reminderList(localDate);
        if (list.isEmpty()) {
            return;
        }
        for (UserCardReminderDTO userCardReminderDTO : list) {
            sendTemplateMessage(userCardReminderDTO);
        }
    }


    private void sendTemplateMessage(UserCardReminderDTO userCardReminderDTO) {
        MsgReceiver receiver = new MsgReceiver();
        //人
        receiver.setId(userCardReminderDTO.getUserId());
        //接收者类型
        receiver.setClassify(MsgReceiver.CLASSIFY_USER);
        receiver.getProperties().addProp("thing1", userCardReminderDTO.getTitle());
        receiver.getProperties().addProp("time2", userCardReminderDTO.getValidityEndTime());
        receiver.getProperties().addProp("thing3", "此卡券将于后天到期，请尽快使用哟！");
        fusionMsgClientService.sendMsg(parkConfigDTO.getDefaultMiniProgramAppId(), null, PandaConstant.T_1004, userCardReminderDTO.getCardMsgId(), userCardReminderDTO.getCardId(), "优惠券到期提醒", PandaConstant.MSG_EVENT_MSG_CLASSIFY_1, receiver, FusionMsg.SEND_FLAG_WEIXIN);
    }
}